<?php
class Lion_View_Helper_Translate extends Zend_Controller_Action_Helper_Abstract
{
    public function translate ($label)
    {
        $sess = new Zend_Session_Namespace('locale');
        $curr_lang = $sess->current_lang;
        $registry = Zend_Registry::getInstance();
        $this->db = $registry->get('db');
        $locale = $curr_lang;
        if($curr_lang != '')
        {
            $lang = $curr_lang;
        } else {
    	    $lang = 'en';
    }
    
    $sql = $this->db->fetchAll("
        SELECT language 
        FROM td_labels
        WHERE contents = '" . $label . "' 
    ");
    
    if(count($sql) == 0)
    {
        $lang = 'en';
    } else {
        $lang = $lang;
    }
    
    $sql4 = $this->db->fetchAll("
        SELECT contents 
        FROM td_labels
        WHERE language = '" . $lang . "'
    ");
    
    if(count($sql4) == 0)
    {
        $lang = 'en';
    } else {
        $lang = $lang;
    }
    
    $sql1 = $this->db->fetchAll("
    	SELECT id 
    	FROM td_labels_key
    	WHERE keyText = '" . $label ."' ");
    
    if(count($sql1) == 0)
    {
        $add_labels = $this->db->query("
		      INSERT
		      INTO td_labels_key(keyText)
		      VALUES ('" . $label . "')");
        $last_insert_id = $this->db->lastInsertId();
        if ($add_labels) {
        	$add_labels_key = $this->db->query("
		        INSERT
		        INTO td_labels
		        VALUES(" . $last_insert_id . ", '" . $lang . "', '" . $label . "', now())");
        }	
    } else {    
        foreach ($sql1 as $result1)
        {
            $id = $result1['id'];
            $sql2 = $this->db->fetchAll("
                SELECT contents
                FROM td_labels
                WHERE language = '" . $lang . "' AND id = '" . $id . "' 
            ");
            
            foreach ($sql2 as $result2)
            {
                $contents = $result2['contents'];
                $contents = str_replace('%', '', $contents);  	
        	    return str_replace('<p>', '', $contents);
            }
            
        }
    }        
    
    /*if(count($sql) == 0)
    {
    	//$curr_lang = 'en';
    	$add_labels = $this->db->query("
		      INSERT
		      INTO td_labels_key(keyText)
		      VALUES ('" . $label . "')");
        $last_insert_id = $this->db->lastInsertId();
        if ($add_labels) {
        	$add_labels_key = $this->db->query("
		        INSERT
		        INTO td_labels
		        VALUES(" . $last_insert_id . ", '" . $lang . "', '" . $label . "', '', now())");
		        
  		$add_version = $this->db->query("
	        INSERT 
	        INTO td_labels_version
			VALUES(" . $last_insert_id . ", '" . $lang . "', '1', '1', '" . $label . "', '', now())");
        }
    }*/
    
    //$string = str_replace('%', '', $label);   	
    	
    //return str_replace('<p>', '', $label);
  }
}
